import Vue from 'vue';
import Vuex from 'vuex';
import { getSiteNav } from '@/api/web/sysWebColumn';
import { getSiteBaseInfo } from '@/api/web/sysBaseInfo';
Vue.use(Vuex)

const state = {
	headerData: {},
	footerData: {},
	siteInfo: {},
	menuData: []
}

const getters = {
	headerData(state) {
		return !state.headerData ? {} : state.headerData;
	},
	footerData(state) {
		return !state.footerData ? {} : state.footerData;
	},
	siteInfo(state) {
		return !state.siteInfo ? {} : state.siteInfo;
	},
	menuData(state) {
		return !state.menuData ? [] : state.menuData;
	}
}

const actions = {
	init: ({ state, commit, dispatch }) => {
		return new Promise(async (resolve, reject) => {
			await dispatch('getSiteInfo');
			await dispatch('getSiteNavData');
			resolve();
		}).catch(() => {
			reject();
		})
	},

	//获取网站基本信息
	async getSiteInfo({ commit }, data) {
		const vueInstance = new Vue();
		const arrayToObject = (arr) => {
			let obj = {};
			Array.from(arr).forEach(item => {
				if (item.type === '1') {
					obj[item.code] = item.value;
				} else if (item.type === '2') {
					obj[item.code] = item.sysAttachment;
				}
			})
			return obj;
		}
		let result = await getSiteBaseInfo().then(res => res.data);
		if (result.code === '0') {
			let datas = arrayToObject(!result.data ? [] : [...result.data])
			document.title = datas['webName'];
			commit('SET_HEADER_DATA', vueInstance.$getAssignAttr(datas, ['logo']));
			commit('SET_SITE_INFO', vueInstance.$getAssignAttr(datas, ['logo', 'webName', 'loginBg', 'articleImg', 'bookImg', 'headPic']));
			commit('SET_FOOTER_DATA', vueInstance.$getAssignAttr(datas, ['botLogo', 'copyright', 'serveInfo']));
		}
	},

	//获取导航菜单
	async getSiteNavData({ commit }, data) {
		let result = await getSiteNav({ classType: '1' }).then(res => res.data);
		if (result.code === '0') {
			commit('SET_MENU_DATA', !result.data ? [] : [...result.data]);
		}
	}
}

const mutations = {
	SET_HEADER_DATA: (state, d) => {
		state.headerData = d;
	},
	SET_FOOTER_DATA: (state, d) => {
		state.footerData = d;
	},
	SET_SITE_INFO: (state, d) => {
		state.siteInfo = d;
	},
	SET_MENU_DATA: (state, d) => {
		state.menuData = d;
	}
}

export default { state, getters, actions, mutations }